<template>
  <a-popover
    :key="popoverKey"
    :open="open"
    trigger="click"
    placement="leftTop"
    :align="{ offset: [16, 16] }"
    :auto-adjust-overflow="false"
    overlay-class-name="z-[888]"
    @open-change="onClose"
  >
    <template #content>
      <div id="itemTempModal" class="w-[820px] flex flex-col" :style="{ height: popoverHeight + 'px' }">
        <a-radio-group v-model:value="formState.advExecType" button-style="solid" class="w-full">
          <a-radio-button :value="0" class="w-1/3 text-center border-t-0">临时</a-radio-button>
          <a-radio-button :value="1" class="w-1/3 text-center !rounded-none border-t-0">长期</a-radio-button>
          <a-radio-button :value="2" class="w-1/3 text-center !rounded-none border-t-0">出院带药</a-radio-button>
        </a-radio-group>
        <a-menu :selected-keys="[formState.boxType]" class="flex menu-style">
          <a-menu-item v-for="(item, index) in typeEnum" :key="item.boxType" :disabled="item.disabled" @click="onSelectType(item)">
            <div class="img-style"><img :src="getIcon(index + 1)" alt="" /></div>
            <div class="menu-title">{{ item.boxType }}</div>
          </a-menu-item>
        </a-menu>
        <a-form :model="formState" class="px-6 pb-[80px] overflow-auto" :label-col="{ style: { width: formState.advExecType === 2 ? '80px' : '120px' } }">
          <div v-if="['全部', '西成药', '处置'].includes(formState.boxType)" class="flex flex-wrap">
            <div class="flex w-full">
              <div class="relative" :class="isSeviceXmlb ? 'w-full' : 'w-1/2'">
                <SelectTable
                  type="处方"
                  placeholder="项目名称/助记码"
                  class-name="pr-40"
                  :auto-focus="autoFocusName === '项目'"
                  :value="formState.adv?.mc"
                  :search-params="{ xmlbList: formState.xmlbList, isInpUse: 1, iskc: 0 }"
                  :table-width="720"
                  @select="onSelectMedicine($event, formState)"
                />
                <div class="absolute h-full flex items-center right-2 top-0 text-xs text-gray-400">
                  <span>{{ formState.adv?.gg }} </span>
                  <span class="ml-2 max-w-[64px] truncate" :title="formState.adv?.cj">{{ formState.adv?.cj }} </span>
                </div>
              </div>
              <div v-show="!isSeviceXmlb" class="flex w-1/2">
                <div class="w-1/3 ml-1 dw-style">
                  <a-input
                    ref="inputNumberRef"
                    v-model:value="formState.count"
                    v-input-selection
                    v-input:float.2
                    :placeholder="formState.boxType === '西成药' ? '剂量' : '数量'"
                    @keydown.enter="onNumEnter"
                  >
                    <template #addonAfter>
                      <a-select
                        ref="unitRef"
                        v-model:value="formState.countUnit"
                        :open="autoFocusName === '单位'"
                        :dropdown-match-select-width="false"
                        option-label-prop="value"
                        placeholder="单位"
                        @blur="autoFocusName = ''"
                        @click="autoFocusName = '单位'"
                        @change="
                          (_, option) => {
                            formState.dwType = option.label
                            autoFocusName = '频次'
                          }
                        "
                        @keydown.enter="autoFocusName = '频次'"
                      >
                        <a-select-option v-if="formState.adv?.jldw" :value="formState.adv?.jldw" label="clinicalDoseUnit">
                          <div class="flex justify-between items-center w-28">
                            <span>{{ formState.adv?.jldw }}</span> <span class="text-gray-400 text-xs">剂量单位</span>
                          </div>
                        </a-select-option>
                        <a-select-option v-if="formState.adv?.dw" :value="formState.adv?.dw" label="unit">
                          <div class="flex justify-between items-center w-28">
                            <span>{{ formState.adv?.dw }}</span> <span class="text-gray-400 text-xs">单位</span>
                          </div>
                        </a-select-option>
                        <a-select-option v-if="formState.adv?.zxdw" :value="formState.adv?.zxdw" label="minimumUnit">
                          <div class="flex justify-between items-center w-28">
                            <span>{{ formState.adv?.zxdw }}</span> <span class="text-gray-400 text-xs">最小单位</span>
                          </div>
                        </a-select-option>
                      </a-select>
                    </template>
                  </a-input>
                </div>
                <SelectTable
                  :value="formState.fqy?.pl"
                  :table-width="360"
                  type="频率"
                  select-first
                  :auto-focus="autoFocusName === '频次'"
                  class="ml-1 w-1/3"
                  placeholder="频次"
                  :disabled="formState.isChild"
                  @select="onSelectFrequency($event, formState)"
                />
                <SelectTable
                  :value="formState.deliverRoute?.fyff"
                  :table-width="360"
                  :auto-focus="autoFocusName === '给药途径'"
                  type="用法"
                  class="w-1/3 ml-1"
                  placeholder="给药途径"
                  :disabled="formState.isChild"
                  @enter="onEnterWays"
                  @select="onSelectWays($event, formState)"
                />
              </div>
            </div>
            <a-divider class="my-3" />
            <!-- 出院带药 -->
            <template v-if="formState.advExecType === 2">
              <a-form-item label="天数" class="w-1/2">
                <a-input-number v-model:value="formState.medicationDay" class="w-full" :min="1" placeholder="请输入" @blur="onCalc" />
              </a-form-item>
              <a-form-item label="总量" class="w-1/2">
                <a-input v-model:value="formState.medicationTotal" v-input:float.2 :addon-after="formState.adv?.dw" class="w-full" placeholder="请输入" />
              </a-form-item>
            </template>
            <template v-if="formState.advExecType !== 2">
              <a-form-item label="开始时间" class="w-1/2">
                <a-date-picker
                  v-model:value="formState.startTime"
                  :disabled="!formState.advExecType"
                  show-time
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm"
                />
              </a-form-item>
              <a-form-item label="结束时间" class="w-1/2">
                <a-date-picker
                  v-model:value="formState.endTime"
                  :disabled="!formState.advExecType"
                  show-time
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm"
                />
              </a-form-item>
              <a-form-item label="首日执行次数" class="w-1/2">
                <a-input-number
                  ref="fristDayRef"
                  v-model:value="formState.fdayExecCount"
                  v-input-selection
                  :disabled="!formState.advExecType"
                  class="w-full"
                  :min="1"
                  placeholder="请输入"
                  @keydown.enter="onSave"
                />
              </a-form-item>
              <a-form-item label="末日执行次数" class="w-1/2">
                <a-input-number
                  v-model:value="formState.ldayExecCount"
                  v-input-selection
                  :disabled="!formState.advExecType"
                  class="w-full"
                  :min="1"
                  placeholder="请输入"
                />
              </a-form-item>
              <a-form-item v-if="formState.boxType !== '处置'" label="首顿执行时间" class="w-1/2">
                <a-time-picker v-model:value="formState.fdayExecTime" :disabled="!formState.advExecType" format="HH:mm" value-format="HH:mm" />
              </a-form-item>
              <a-form-item v-if="formState.boxType !== '处置'" label="" class="w-1/5 text-center">
                <a-checkbox v-model:checked="formState.drugPathChecked" @change="formState.drugPath = formState.drugPathChecked ? 1 : 0"> 自备 </a-checkbox>
              </a-form-item>
              <a-form-item v-if="formState.advExecType !== 1" label="" :class="formState.boxType === '处置' ? 'w-1/2 text-center' : 'w-1/5'">
                <a-checkbox v-model:checked="isOperationUse" @change="onIsOperationUse"> 术中用 </a-checkbox>
              </a-form-item>
              <a-form-item label="部位" class="w-1/2">
                <!-- <a-select v-model:value="formState.partCode" placeholder="请选择" :options="partData" allow-clear /> -->
                <SelectPartTags
                  :value="{ partCode: formState.partCodeList, partName: formState.partName }"
                  multiple
                  allow-clear
                  show-new
                  :input-or-textarea="true"
                  type="部位"
                  @select=";(formState.partCodeList = $event.partCode || []), (formState.partName = $event.partName)"
                />
              </a-form-item>
              <a-form-item label="执行科室" class="w-1/2">
                <a-input v-if="defaultOperationCode && isOperation" v-model:value="defaultOperationName" placeholder="默认手术科室配置错误" disabled />
                <a-select v-else v-model:value="formState.execDeptCode" placeholder="请选择" :options="formState.adv?.execDeptInfo" allow-clear />
              </a-form-item>
            </template>
            <a-form-item :label="formState.advExecType === 2 ? '医生说明' : '嘱托'" class="w-full">
              <a-textarea v-model:value="formState.advMemo" placeholder="请输入" :rows="formState.advExecType === 2 ? 3 : 1" />
            </a-form-item>
            <div class="px-5 w-full">
              <div class="flex items-center justify-center mb-4">
                <a-button
                  v-if="[2, 4].includes(formState.adv?.xmlb) || formState.boxType === '西成药'"
                  type="primary"
                  ghost
                  :icon="h(PlusOutlined)"
                  @click="onAddChild"
                >
                  子医嘱
                </a-button>
              </div>
              <div v-for="(childItem, index) in formState.children" :key="index" class="py-2 border-t">
                <div class="flex justify-between items-center">
                  <div>子医嘱{{ index + 1 }}</div>
                  <a-button type="link" danger size="small" :icon="h(DeleteOutlined)" @click="onDeleteChild(index)" />
                </div>
                <div class="flex items-center mt-2">
                  <div class="w-2/3 relative">
                    <SelectTable
                      type="处方"
                      class-name="pr-40"
                      :auto-focus="autoFocusName === '子项目' + index"
                      placeholder="项目名称/助记码"
                      :value="childItem.adv?.mc"
                      :search-params="{ xmlbList: [2, 4], isInpUse: 1, iskc: 0 }"
                      :table-width="720"
                      @select="onSelectMedicine($event, childItem, true, index)"
                    />
                    <div class="absolute h-full flex items-center right-2 top-0 text-xs text-gray-400">
                      <span>{{ childItem.adv?.gg }} </span>
                      <span class="ml-2 max-w-[64px] truncate" :title="childItem.adv?.cj">{{ childItem.adv?.cj }} </span>
                    </div>
                  </div>
                  <div class="flex-1 ml-2 dw-style">
                    <a-input
                      :ref="(e) => setSubRef(e, 'numRef', index)"
                      v-model:value="childItem.count"
                      v-input:float.2
                      placeholder="剂量"
                      @keydown.enter="onSubNumEnter(index, childItem)"
                    >
                      <template #addonAfter>
                        <a-select
                          :ref="(e) => setSubRef(e, 'unitRef', index)"
                          v-model:value="childItem.countUnit"
                          :dropdown-match-select-width="false"
                          option-label-prop="value"
                          placeholder="单位"
                          :open="autoFocusName === '单位' + index"
                          :disabled="!childItem.adv?.mc"
                          @click="autoFocusName = '单位' + index"
                          @blur="autoFocusName = ''"
                          @change="
                            (_, option) => {
                              childItem.dwType = option.label
                              onAddChild()
                            }
                          "
                          @keydown.enter="onAddChild"
                        >
                          <a-select-option v-if="childItem.adv?.jldw" :value="childItem.adv?.jldw" label="clinicalDoseUnit">
                            <div class="flex justify-between items-center w-28">
                              <span>{{ childItem.adv?.jldw }}</span> <span class="text-gray-400 text-xs">剂量单位</span>
                            </div>
                          </a-select-option>
                          <a-select-option v-if="childItem.adv?.dw" :value="childItem.adv?.dw" label="unit">
                            <div class="flex justify-between items-center w-28">
                              <span>{{ childItem.adv?.dw }}</span> <span class="text-gray-400 text-xs">单位</span>
                            </div>
                          </a-select-option>
                          <a-select-option v-if="childItem.adv?.zxdw" :value="childItem.adv?.zxdw" label="minimumUnit">
                            <div class="flex justify-between items-center w-28">
                              <span>{{ childItem.adv?.zxdw }}</span> <span class="text-gray-400 text-xs">最小单位</span>
                            </div>
                          </a-select-option>
                        </a-select>
                      </template>
                    </a-input>
                  </div>
                  <div class="w-20 ml-2 text-center">
                    <a-checkbox v-model:checked="childItem.drugPathChecked" @change="childItem.drugPath = childItem.drugPathChecked ? 1 : 0"> 自备 </a-checkbox>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div v-if="formState.boxType === '转区'" class="mt-4 w-full flex flex-wrap">
            <a-form-item label="接收科室" class="w-1/2" required>
              <SelectSection v-model:value="formState.inpTransferZone.destDeptCode" @change="(_, name) => (formState.inpTransferZone.destDeptName = name)" />
            </a-form-item>
            <a-form-item label="接收病区" class="w-1/2" required>
              <SelectArea v-model:value="formState.inpTransferZone.destWardId" @change="(_, name) => (formState.inpTransferZone.destWardName = name)" />
            </a-form-item>
            <a-form-item label="转区时间" class="w-1/2" required>
              <a-date-picker v-model:value="formState.inpTransferZone.transferDate" value-format="YYYY-MM-DD" />
            </a-form-item>
            <a-form-item label=" " class="w-1/2">
              <a-radio-group
                v-model:value="formState.inpTransferZone.ampm"
                :options="[
                  { label: 'AM', value: 0 },
                  { label: 'PM', value: 1 }
                ]"
              />
            </a-form-item>
          </div>
          <div v-if="formState.boxType === '出院'" class="mt-4 w-full flex flex-wrap">
            <a-form-item label="出院情况" class="w-1/2" required>
              <SelectItem
                v-model:value="formState.inpDischarge.dischargeDscCode"
                type="DT00030"
                @change="(_, select) => (formState.inpDischarge.dischargeDsc = select.label)"
              />
            </a-form-item>
            <a-form-item label="出院方式" class="w-1/2" required>
              <SelectItem
                v-model:value="formState.inpDischarge.dischargeWayCode"
                type="DT00031"
                @change="(_, select) => (formState.inpDischarge.dischargeWay = select.label)"
              />
            </a-form-item>
            <a-form-item label="出院时间" class="w-1/2" required>
              <a-date-picker v-model:value="formState.inpDischarge.dischargeDate" value-format="YYYY-MM-DD" />
            </a-form-item>
            <a-form-item label=" " class="w-1/2">
              <a-radio-group
                v-model:value="formState.inpDischarge.ampm"
                :options="[
                  { label: 'AM', value: 0 },
                  { label: 'PM', value: 1 }
                ]"
              />
            </a-form-item>
          </div>
          <a-form-item v-if="['出院', '转区'].includes(formState.boxType)" label="嘱托" class="w-full">
            <a-textarea v-model:value="formState.advMemo" placeholder="请输入" :rows="6" />
          </a-form-item>
          <a-form-item v-if="['嘱托'].includes(formState.boxType)" label="嘱托" class="w-full">
            <a-textarea v-model:value="formState.advName" placeholder="请输入" :rows="8" />
          </a-form-item>
          <a-form-item v-if="['其他', '中草药'].includes(formState.boxType)" class="w-full">
            {{ formState.boxType }}
          </a-form-item>
          <div v-if="formState.boxType === '出院'" class="mt-4 w-full flex flex-wrap">
            <a-form-item label="病种" class="w-full">
              <a-input-group compact class="w-full">
                <SelectTable
                  v-model:value="formState.inpDischarge.diseaseTypeName"
                  type="病种"
                  placeholder="病种代码"
                  class="!w-1/2"
                  @select=";(formState.inpDischarge.diseaseTypeName = $event.zdmc), (formState.inpDischarge.diseaseTypeCode = $event.zddm)"
                />
                <a-form-item-rest>
                  <a-input v-model:value="formState.inpDischarge.diseaseTypeCode" class="!w-1/2" :disabled="true" placeholder="病种名称" />
                </a-form-item-rest>
              </a-input-group>
            </a-form-item>
            <a-form-item label="手术操作" class="w-full">
              <a-input-group compact class="w-full">
                <SelectTable
                  v-model:value="formState.inpDischarge.icd9Name"
                  type="手术"
                  placeholder="手术代码"
                  class="!w-1/2"
                  @select=";(formState.inpDischarge.icd9Name = $event.mc), (formState.inpDischarge.icd9Code = $event.bh)"
                />
                <a-form-item-rest>
                  <a-input v-model:value="formState.inpDischarge.icd9Code" class="!w-1/2" :disabled="true" placeholder="手术名称" />
                </a-form-item-rest>
              </a-input-group>
            </a-form-item>
            <a-form-item label="死亡日期" class="w-1/2">
              <a-date-picker v-model:value="formState.inpDischarge.deathTime" value-format="YYYY-MM-DD" />
            </a-form-item>
            <a-form-item label="生育类别" class="w-1/2" :label-col="{ style: { width: '180px' } }">
              <SelectItem v-model:value="formState.inpDischarge.fertilityId" type="birctrl_type" />
            </a-form-item>
            <a-form-item label="计划生育手术类别" class="w-1/2" :label-col="{ style: { width: '140px' } }">
              <SelectItem v-model:value="formState.inpDischarge.fertilityOperId" type="matn_type" />
            </a-form-item>
            <a-form-item label="计划生育手术或生育时间" class="w-1/2" :label-col="{ style: { width: '180px' } }">
              <a-date-picker v-model:value="formState.inpDischarge.fertilityOperTime" value-format="YYYY-MM-DD" />
            </a-form-item>
            <a-form-item label="计划生育服务证号" class="w-1/2" :label-col="{ style: { width: '140px' } }">
              <a-input v-model:value="formState.inpDischarge.fertilityOperNo" placeholder="请输入" />
            </a-form-item>
            <a-form-item label="孕周数" class="w-1/6" :label-col="{ style: { width: '68px' } }">
              <a-input v-model:value="formState.inpDischarge.pregnantWeek" placeholder="请输入" />
            </a-form-item>
            <a-form-item label="胎次" class="w-1/6" :label-col="{ style: { width: '68px' } }">
              <a-input v-model:value="formState.inpDischarge.fetusIndex" placeholder="请输入" />
            </a-form-item>
            <a-form-item label="胎儿数" class="w-1/6" :label-col="{ style: { width: '68px' } }">
              <a-input v-model:value="formState.inpDischarge.fetusNumber" placeholder="请输入" />
            </a-form-item>
            <a-form-item label="" class="w-1/2 pl-4">
              <a-checkbox v-model:checked="formState.inpDischarge.isPremature">早产</a-checkbox>
              <a-checkbox v-model:checked="formState.inpDischarge.isLateMarriage">晚育</a-checkbox>
              <a-checkbox v-model:checked="formState.inpDischarge.isComplication">伴有并发症</a-checkbox>
            </a-form-item>
          </div>
          <div v-if="formState.boxType === '检验'" class="mt-4 w-full flex flex-col">
            <div class="flex justify-end">
              <a-button type="primary" @click="laboratoryOpen = true">新增</a-button>
            </div>
            <div class="flex-1">
              <div
                v-for="(item, index) in laboratoryList"
                :key="index"
                class="flex justify-between items-center bg-secondary border border-blue-600 p-2 mt-4 rounded"
              >
                <div>
                  <div class="text-lg font-bold">
                    {{ item.categroyName }}
                  </div>
                  <div>
                    {{ item.orderItemNames }}
                  </div>
                </div>
                <div>
                  <a-button type="link" @click="onUpdateLaboratory(item)">修改</a-button>
                  <BaseButton type="link" danger confirm-text="确认删除?" @click="onDeleteLaboratory(item)">删除</BaseButton>
                </div>
              </div>
              <a-empty v-if="!laboratoryList.length" />
            </div>
          </div>
        </a-form>

        <a-space class="absolute bottom-0 flex justify-end bg-white py-6 px-8 w-full">
          <a-button @click="onCancel">取消</a-button>
          <a-button type="primary" @click="onSave">保存</a-button>
        </a-space>
      </div>
      <LaboratoryModal v-model:open="laboratoryOpen" :laboratory-data="currentLaboratory" :get-container="getContainer" @success="onLaboratorySuccess" />
    </template>
  </a-popover>
</template>

<script setup>
import { ref, watch, h, computed } from 'vue'
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { debounce } from 'lodash-es'

import dayjs from 'dayjs'
import useStore from '../suit-template/store'
import LaboratoryModal from './LaboratoryModal'

const getContainer = () => document.getElementById('itemTempModal')
const store = useStore()
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  popoverHeight: {
    type: Number,
    default: 0
  },
  rowData: {
    type: Object,
    default: () => ({})
  },
  isOperation: {
    type: Boolean,
    default: false
  }
})
const autoFocusName = ref()
const fristDayRef = ref(null)
const currentLaboratory = ref({})
const unitRef = ref(null)
const laboratoryOpen = ref(false)
const inputNumberRef = ref(null)
const getIcon = (name) => {
  return new URL(`/src/assets/icons/icon-item-${name}.png`, import.meta.url).href
}
const emit = defineEmits(['update:open', 'refresh'])
const lastDate = ref({
  advExecType: 0,
  boxType: ''
})
const typeEnum = [
  { boxType: '全部', boxTypeValue: 0, xmlbList: [2, 4, 41, 42, 10, 11, 0, 3, 7, 8, 20, 22, 23, 30, 99, 1, 51, 6] },
  { boxType: '西成药', boxTypeValue: 0, xmlbList: [2, 4] },
  { boxType: '中草药', boxTypeValue: 0, disabled: true, xmlbList: [5] },
  { boxType: '处置', boxTypeValue: 0, xmlbList: [41, 42, 10, 11, 0, 3, 7, 8, 20, 22, 23, 30, 99, 1, 51, 6] },
  { boxType: '嘱托', boxTypeValue: 0, xmlbList: [] },
  { boxType: '检验', boxTypeValue: 1, xmlbList: [] },
  { boxType: '检查', boxTypeValue: 3, disabled: true, xmlbList: [] },
  { boxType: '其他', boxTypeValue: 0, disabled: true, xmlbList: [7, 8, 99] }
]
const defaultRow = () => {
  return {
    startTime: dayjs().format('YYYY-MM-DD HH:mm'),
    adv: { xmlb: 2 },
    advExecType: 0, //医嘱执行类别;0：临时 1：长期 2：出院带药
    cydy: 0,
    status: 0,
    advType: 0, //医嘱类别;0:收费医嘱|1：口头医嘱
    boxType: '全部',
    drugPath: 0,
    inpAdviceType: props.isOperation ? '1' : '0', //0住院医嘱 1术后医嘱
    inpTransferZone: { ampm: 0 },
    inpDischarge: { ampm: 0 },
    xmlbList: typeEnum[0].xmlbList,
    children: []
  }
}
const formState = ref({ ...defaultRow() })

const onCancel = () => {
  emit('update:open', false)
}
watch(
  () => props.open,
  (val) => {
    if (val) {
      autoFocusName.value = ''
      const rowData = { ...props.rowData }
      rowData.drugPathChecked = rowData.drugPath === 1
      rowData.children?.forEach((child) => {
        child.drugPathChecked = child.drugPath === 1
      })
      if (rowData.inpDischarge) {
        formState.value = {
          ...defaultRow(),
          ...rowData,
          inpDischarge: {
            ...rowData.inpDischarge,
            isPremature: rowData.inpDischarge.isPremature === '1' ? true : false,
            isLateMarriage: rowData.inpDischarge.isLateMarriage === '1' ? true : false,
            isComplication: rowData.inpDischarge.isComplication === '1' ? true : false
          }
        }
      } else {
        formState.value = { ...defaultRow(), ...rowData }
      }
      formState.value.advExecType = lastDate.value.advExecType
      formState.value.boxType = rowData.boxType || lastDate.value.boxType || '全部'
      if (rowData.boxType) {
        formState.value.xmlbList = typeEnum.find((item) => item.boxType === rowData.boxType)?.xmlbList
      } else {
        formState.value.xmlbList = lastDate.value.xmlbList || typeEnum[0].xmlbList
      }
      formState.value.boxType === '检验' && getLaboratoryList()
    } else {
      lastDate.value = {
        boxType: formState.value.boxType || '全部',
        xmlbList: formState.value.xmlbList || typeEnum[0].xmlbList,
        advExecType: formState.value.advExecType
      }
    }
  }
)
const onCalc = async () => {
  if (
    !formState.value.count ||
    !formState.value.fqy?.sl ||
    !formState.value.countUnit ||
    !formState.value.medicationDay ||
    !formState.value.adv.bh ||
    formState.value.advExecType !== 2
  )
    return
  const { data, code } = await post('/inp/clinicalOrder/dischargeWithMedicationCalculateTotalCount', {
    bh: formState.value.adv.bh,
    count: formState.value.count,
    day: formState.value.medicationDay,
    dwType: formState.value.dwType,
    sl: formState.value.fqy?.sl
  })
  if (code !== 0) return message.error('计算失败')
  formState.value.medicationTotal = data
}
//选用法
const onSelectWays = (selected, row) => {
  row.deliverRoute = selected
  formState.value.advExecType === 1 && onFocusFristDayRef()
}
const onFocusFristDayRef = () => {
  setTimeout(() => {
    fristDayRef.value.focus()
    fristDayRef.value.$el.querySelector('input')?.setSelectionRange(0, 99)
  }, 10)
}
//选频率
const onSelectFrequency = (selected, row) => {
  row.fqy = selected
  row.pltimeList = selected.dictDrugFqcTimes?.map((item) => item.frequencyTime)
  if (!selected.autoSelected) {
    autoFocusName.value = '给药途径'
  }
  // row.boxType === '处置' ? onFocusFristDayRef() : (autoFocusName.value = '给药途径')
  // row.children?.length && row.children?.forEach((item) => (item.fqy = selected))
}
const onNumEnter = () => {
  unitRef.value.$el.querySelector('input').focus()
  autoFocusName.value = '单位'
}
const onSubNumEnter = (index) => {
  autoFocusName.value = '单位' + index
  subRef.value['unitRef' + index]?.$el.querySelector('input').focus()
}
const subRef = ref({})
const setSubRef = (e, name, index) => {
  subRef.value[name + index] = e
}
// advCode: formState.value.adv.bh,
// advName: formState.value.adv.mc,
//选择处置项目
const onSelectMedicine = (data, item, isChild = false, index = 0) => {
  item.adv = data
  if (data.jldw) {
    item.countUnit = data.jldw
    item.dwType = 'clinicalDoseUnit'
  } else if (data.dw) {
    item.countUnit = data.dw
    item.dwType = 'unit'
  } else if (data.zxdw) {
    item.countUnit = data.zxdw
    item.dwType = 'minimumUnit'
  }
  if (data.xmlb === 7) {
    item.count = 1
  }
  if (isChild) {
    subRef.value['numRef' + index]?.focus()
    item.advCode = item.adv.bh
    item.advName = item.adv.mc
  } else {
    setTimeout(() => {
      inputNumberRef.value?.focus()
      inputNumberRef.value?.$el.querySelector('input')?.setSelectionRange(0, 99)
    }, 10)
  }
  if (props.isOperation && defaultOperationCode) {
    item.execDeptCode = defaultOperationCode
  } else {
    item.execDeptCode = data.execDeptInfo?.[0]?.value || null
  }
}
//选择类型
const onSelectType = (item) => {
  autoFocusName.value = ''
  formState.value = {
    ...defaultRow(),
    adv: {},
    advOrderType: item.boxTypeValue,
    xmlbList: item.xmlbList,
    boxType: item.boxType,
    boxTypeValue: item.boxTypeValue,
    advExecType: ['转区', '出院', '嘱托'].includes(item.boxType) ? 0 : formState.value.advExecType
  }
  if (item.boxType === '检验') {
    getLaboratoryList()
  }
}

//添加子医嘱
const onAddChild = () => {
  // if (!formState.value?.adv) return message.error('请填写主医嘱')
  const key = `sub-${formState.value.children.length}`
  const extendParams = {
    deliverRoute: formState.value.deliverRoute,
    fqy: formState.value.fqy,
    advExecType: formState.value.advExecType,
    // clinicalDoseUnit: formState.value.clinicalDoseUnit,
    startTime: formState.value.startTime,
    endTime: formState.value.endTime,
    fdayExecCount: formState.value.fdayExecCount,
    ldayExecCount: formState.value.ldayExecCount,
    boxType: '西成药',
    xmlbList: [2, 4],
    drugPath: 0,
    fdayExecTime: formState.value.fdayExecTime
  }
  const newRow = { key, isChild: true, isNew: true, ...defaultRow(), ...extendParams }
  formState.value.children.push(newRow)
  autoFocusName.value = '子项目' + (formState.value.children.length - 1)
}

const onSave = async () => {
  if (formState.value.boxType === '检验') {
    return
  }
  let params = {}
  if (formState.value.children.length > 0) {
    formState.value.children = formState.value.children.filter((item) => item.adv?.mc) //删除空白子医嘱
  }
  if (['全部', '西成药', '处置'].includes(formState.value.boxType)) {
    const { count = 0, countUnit = '', fqy = { pl: '' } } = formState.value
    if (count && countUnit && fqy.pl) {
      params = formState.value
    } else {
      return message.error('请输入完整')
    }
    // if (formState.value.boxType === '全部' && formState.value.adv.xmlb) {
    //   formState.value.boxType = typeEnum.find((item) => item.xmlbList.includes(formState.value.adv.xmlb)).boxType
    // }
  }
  if (formState.value.boxType === '转区') {
    if (formState.value.inpTransferZone.destDeptCode && formState.value.inpTransferZone.destWardId && formState.value.inpTransferZone.transferDate) {
      params = formState.value
    } else {
      return message.error('请输入完整')
    }
  }
  if (formState.value.boxType === '出院') {
    if (formState.value.inpDischarge.dischargeDscCode && formState.value.inpDischarge.dischargeWayCode && formState.value.inpDischarge.dischargeDate) {
      params = {
        ...formState.value,
        inpDischarge: {
          ...formState.value.inpDischarge,
          isPremature: formState.value.inpDischarge.isPremature ? '1' : '0',
          isLateMarriage: formState.value.inpDischarge.isLateMarriage ? '1' : '0',
          isComplication: formState.value.inpDischarge.isComplication ? '1' : '0'
        }
      }
    } else {
      return message.error('请输入完整')
    }
  }
  if (formState.value.boxType === '嘱托') {
    if (formState.value.advName) {
      params = { ...formState.value }
      params.advType = 1
    } else {
      return message.error('请输入完整')
    }
  }
  // const { code, msg } = await post('/inp/clinicalOrder/doSavePatientClinicalOrder', params)
  // if (code !== 0) return message.error(msg || '保存失败')
  // message.success('保存成功')
  const data = {
    ...params,
    advOrderType: 0,
    advCode: params.adv?.bh, //主医嘱编码
    advName: params.adv?.mc, //医嘱名称
    deliverRouteCode: params.deliverRoute?.fyffid, //给药途径代码
    fqyCft: params.fqy?.sl, //频率系数
    fqyCode: params.fqy?.plid, //频率代码
    inpAdviceTemplateId: store.currentSuit.id, //医嘱模板编号
    spc: params.adv?.gg //规格
  }
  if (formState.value.boxType === '嘱托') {
    data.advName = params.advName
  }
  const { code, msg } = await post('/inp/zyys/saveInpAdviceTemplateItem', data)
  if (code !== 0) return message.error(msg || '保存失败')
  message.success('保存成功')

  formState.value = {
    ...defaultRow(),
    boxType: formState.value.boxType,
    xmlbList: typeEnum.find((item) => item.boxType === formState.value.boxType).xmlbList,
    advExecType: formState.value.advExecType
  }
  isOperationUse.value = false
  emit('refresh')
  if (['全部', '西成药', '处置'].includes(formState.value.boxType)) {
    autoFocusName.value = '项目'
  }
}
const onLaboratorySuccess = async (params) => {
  const data = {
    ...defaultRow(),
    ...params,
    advOrderType: 4,
    boxType: '检验',
    inpAdviceTemplateId: store.currentSuit.id //医嘱模板编号
  }
  const { code, msg } = await post('/inp/zyys/saveInpAdviceTemplateItem', data)
  if (code !== 0) return message.error(msg || '保存失败')
  message.success('保存成功')
  getLaboratoryList()
  emit('refresh')
}
const laboratoryList = ref([])
const getLaboratoryList = async () => {
  const { code, msg, data } = await post('/inp/zyys/getLisInpTemplateList', { inpAdviceTemplateId: store.currentSuit.id })
  if (code !== 0) return message.error(msg)
  laboratoryList.value = data
}

//选用法
const onEnterWays = () => {
  setTimeout(() => {
    formState.value.advExecType === 0 && onSave()
  }, 100)
}
const onDeleteChild = (index) => {
  formState.value.children.splice(index, 1)
}
// const { tableData: listData } = useTable({
//   url: '/inp/zyys/getLisInpTemplateList',
//   formatParams: () => {
//     return {
//       inpAdviceTemplateId: props.inpAdviceTemplateId
//     }
//   }
// })

watch(
  () => formState.value.advExecType,
  (val) => {
    typeEnum.forEach((item) => {
      if (val === 2) {
        if (item.boxType === '西成药') {
          item.disabled = false
          formState.value.boxType = '西成药'
          onSelectType(item)
        } else {
          item.disabled = true
        }
      } else {
        if (item.boxType === '中草药' || item.boxType === '其他') {
          item.disabled = true
        } else {
          item.disabled = false
        }
      }
    })
  }
)
const onClose = (visible) => {
  emit('update:open', visible)
}
watch(
  () => formState.value.fdayExecCount,
  (val) => {
    if (val && formState.value.pltimeList && formState.value.advExecType) {
      const today = dayjs().format('YYYY-MM-DD')
      const startDayNum = +new Date(formState.value.startTime)
      formState.value.fdayExecTime = formState.value.pltimeList[0]
      for (let index = 0; index < formState.value.pltimeList.length; index++) {
        const element = formState.value.pltimeList[index]
        const actionTime = +new Date(today + ' ' + element)
        if (actionTime >= startDayNum) {
          formState.value.fdayExecTime = element
          break
        }
      }
    }
  }
)
const onUpdateLaboratory = (row) => {
  currentLaboratory.value = row
  laboratoryOpen.value = true
}
const onDeleteLaboratory = async (row) => {
  const { code, msg } = await post('/inp/zyys/delInpAdviceTemplateInspectionCategories', { id: row.id })
  if (code !== 0) return message.error(msg || '删除失败')
  message.success('删除成功')
  getLaboratoryList()
  emit('refresh')
}
const isOperationUse = ref(false)
const onIsOperationUse = () => {
  formState.value.advType = isOperationUse.value ? 1 : 0
}

const popoverKey = ref(new Date().getTime())
const defaultOperationCode = getSystemConfig('OPERATION_DEPT_CODE')
const defaultOperationName = ref('')
const isSeviceXmlb = computed(() => {
  return formState.value.adv?.xmlb === 7 && getSystemConfig('INP_NURSING_ADVICE_IS_SHOW_FREQ') === '1'
})
onMounted(async () => {
  const { code, data } = await post('/common/emp/getKsmcByKsdm', { ksdm: defaultOperationCode })
  if (code !== 0) return
  defaultOperationName.value = data || ''
  window.onresize = debounce(() => {
    popoverKey.value = new Date().getTime()
  }, 500)
})
</script>
<style lang="less" scoped>
.ant-form {
  display: flex;
  flex-flow: row wrap;
  min-width: 0;
  .ant-picker {
    width: 100%;
  }
}
.header {
  background: var(--thin-color);
}
.dw-style {
  :deep(.ant-select-selector) {
    width: 64px;
    padding: 0 8px;
  }
}
.ant-menu-item-disabled {
  .img-style {
    opacity: 0.5;
  }
}
.menu-style {
  margin-bottom: 8px;
  border-bottom: 1px solid var(--border-color);
  .img-style {
    img {
      width: 20px;
      height: 20px;
    }
  }

  :deep(.ant-menu-item) {
    height: 68px;
    text-align: center;
  }
  .menu-title {
    line-height: 20px;
  }
}
// .menu-item {
//   width: 66px;
//   height: 60px;
//   margin-right: 2px !important;
//   .ant-dropdown-menu-title-content {
//     display: flex;
//     flex-direction: column;
//     align-items: center;
//     justify-content: center;
//   }
//   &.ant-dropdown-menu-item-disabled {
//     filter: opacity(0.5);
//   }
// }
</style>
